package com.lhfeiyu.action.back.auction;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.lhfeiyu.config.Page;
import com.lhfeiyu.config.Table;
import com.lhfeiyu.dao.AuctionInstMapper;
import com.lhfeiyu.po.AuctionInst;
import com.lhfeiyu.po.AuctionProfession;
import com.lhfeiyu.po.base.BaseAdmin;
import com.lhfeiyu.po.base.BaseUser;
import com.lhfeiyu.service.AuctionInstService;
import com.lhfeiyu.service.AuctionProfessionService;
import com.lhfeiyu.service.base.BaseAA_UtilService;
import com.lhfeiyu.service.base.BaseCommonFundService;
import com.lhfeiyu.service.base.BaseUserService;
import com.lhfeiyu.tools.base.ActionUtil;
import com.lhfeiyu.tools.base.Result;
@Controller
@RequestMapping(value="/back")
public class BackAuctionProfessionAction {
	@Autowired
	private AuctionProfessionService auctionProfessionService;
	@Autowired
	private AuctionInstService auctionInstService;
	@Autowired
	private BaseAA_UtilService utilService;
	@Autowired
	private BaseCommonFundService cfService;
	@Autowired
	private BaseUserService userService;
	private static Logger logger = Logger.getLogger("R");
	
	@RequestMapping(value="/page/auctionProfession", method=RequestMethod.GET)
	public ModelAndView backAuctionProfessionInfo(ModelMap modelMap,HttpServletRequest request) {
		return new ModelAndView(Page.backAuctionProfession);
	}
	
	@ResponseBody
	@RequestMapping(value="/getAuctionProfessionList",method=RequestMethod.POST)
	public JSONObject getAuctionProfessionList(HttpServletRequest request,HttpServletResponse response) {
		List<AuctionProfession> auctionProfessionList = null;
		JSONObject json = new JSONObject();
		try {
			Map<String, Object> map = ActionUtil.getAllParam(request);
		
			auctionProfessionList = auctionProfessionService.selectListByCondition(map);
			Integer total = auctionProfessionService.selectCountByCondition(map);
			json.put("rows", auctionProfessionList);
			json.put("total", total);
			json.put("status", "success");
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_获取拍卖机构出现异常_", json);
		}
		return Result.success(json);
	}
	
	/*@ResponseBody
	@RequestMapping(value="/getAuctionProfession")
	public JSONArray getAuctionProfession(HttpServletRequest request) {
		JSONArray array = new JSONArray();
		try {
			List<AuctionProfession> auctionProfessionList = auctionProfessionService.selectListByCondition(null);
			for(AuctionProfession u : auctionProfessionList){
				JSONObject json = new JSONObject();
				json.put("id",u.getId());
				json.put("name",u.getAuctionProfessionname());
				array.add(json);
			}
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_获取拍卖机构出现异常_", array);
		}
		return array;
	}*/
	
	@ResponseBody
	@RequestMapping(value="/addOrUpdateAuctionProfession", method=RequestMethod.POST)
	public JSONObject addOrUpdateAuctionProfession(@ModelAttribute AuctionProfession auctionProfession,HttpServletRequest request) {
		JSONObject json = new JSONObject();
		try {
			//Admin admin = (Admin) request.getSession().getAttribute("admin");
			BaseAdmin admin = ActionUtil.checkSession4Admin(request.getSession());//验证session中的user，存在即返回
			//auctionProfession.setUpdatedBy(admin.getAuctionProfessionname());
			Date d = new Date();
			BigDecimal money = auctionProfession.getSpreadPackets();
			boolean moneyFlag = true;
			if(null == money || money.doubleValue() <= 0){
				moneyFlag = false;
			}
			if(null != auctionProfession.getId()){//更新
				Integer apId = auctionProfession.getId();
				AuctionProfession dbAP = auctionProfessionService.selectByPrimaryKey(apId);//先查询出专场
				BigDecimal dbMoney = dbAP.getSpreadPackets();
				boolean dbMoneyFlag = true;
				if(null == dbMoney || dbMoney.doubleValue() <= 0){
					dbMoneyFlag = false;
				}
				boolean isUpdateMoney = true;
				if(moneyFlag || dbMoneyFlag){//推广金额不为空 冻结推广金额
					double totalMoney = 0;
					boolean isAdd = true;
					if(moneyFlag && !dbMoneyFlag){//新增推广金额
						totalMoney = money.doubleValue();
					}else if(!moneyFlag && dbMoneyFlag){//删除推广金额
						totalMoney = dbMoney.doubleValue();
						isAdd = false;
					}else if(moneyFlag && dbMoneyFlag){//改变推广金额 - 计算
						double moneyD = money.doubleValue();
						double dbMoneyD = dbMoney.doubleValue();
						if(moneyD > dbMoneyD){
							totalMoney = moneyD - dbMoneyD;
						}else if(moneyD < dbMoneyD){
							totalMoney = dbMoneyD - moneyD  ;
							isAdd = false;
						}else if(moneyD == dbMoneyD){
							isUpdateMoney = false;
						}
					}
					if(isUpdateMoney){
						if(isAdd){
							//TODO 修改
							//json = cfService.freezeMoney(null, new BigDecimal(totalMoney), userId, userName, 151, null, "平台冻结", json, true,null);
						}else{
							//TODO 修改
							//json = cfService.activateMoney(null, new BigDecimal(totalMoney), userId, userName, 151, null, "平台解冻", json, true,null);
						}
					}
					if(json.containsKey("error_desc")){ return Result.success(json); }
				}
				auctionProfession.setUpdatedAt(d); 
				auctionProfession.setUpdatedBy(admin.getUsername());
				auctionProfessionService.updateByPrimaryKeySelective(auctionProfession);
			}else{//新增
				//TODO 修改
				//json = cfService.freezeMoney(null, money, userId, userName, 151, null, "平台冻结", json, true,null);
				if(json.containsKey("error_desc")){ return Result.success(json); }
				auctionProfession.setCreatedAt(d); 
				auctionProfession.setCreatedBy(admin.getUsername());
				auctionProfessionService.insert(auctionProfession);
			}
			json.put("status", "success");
			json.put("msg", "操作成功");
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_新增修改拍卖机构出现异常_", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/updateAuctionProfessionDelete",method=RequestMethod.POST)
	public JSONObject updateAuctionProfessionDelete(HttpServletRequest request,
			@RequestParam(value="ids") String ids) {
		JSONObject json = new JSONObject();
		try {
			//Admin admin = (Admin) request.getSession().getAttribute("admin");
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("table", Table.auction_profession);
			map.put("ids", ids);
			
			utilService.updateDeletedNowByIds(map);
			json.put("status","success");
			json.put("msg","删除成功");
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_删除用户出现异常_", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/deleteAuctionProfessionThorough",method=RequestMethod.POST)
	public JSONObject deleteAuctionProfessionThrough(HttpServletRequest request,
			@RequestParam(value="ids") String ids) {
		JSONObject json = new JSONObject();
		try {
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("table", Table.auction_profession);
			map.put("ids", ids);
			utilService.deleteByIds(map);
			json.put("status","success");
			json.put("msg","彻底删除成功");
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_彻底删除用户出现异常_", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/updateAuctionProfessionRecover",method=RequestMethod.POST)
	public JSONObject updateAuctionProfessionRecover(HttpServletRequest request,
			@RequestParam(value="ids") String ids) {
		JSONObject json = new JSONObject();
		try {
			//Admin admin = (Admin) request.getSession().getAttribute("admin");
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("table", Table.auction_profession);
			map.put("ids", ids);
			//map.put("auctionProfessionname",auctionProfession.getAuctionProfessionname());
			utilService.updateDeletedNullByIds(map);
			json.put("status","success");
			json.put("msg","恢复成功");
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_恢复用户出现异常_", json);
		}
		return Result.success(json);
	}
	
}
